package com.example.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题目: 三个售票员  卖出   30张票
 * <p>
 * JUC
 * <p>
 * 1.  在高内聚低耦合的前提下 ,线程    操作(对外暴露的调用方法)   资源类
 * <p>
 * 2.
 */
class Ticket { //资源类
    private int number = 1000;
    private final Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第:" + number-- + "\t还剩下:" + number);
            }
        } finally {
            lock.unlock();
        }
    }
}

public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        //线程状态(新建,可运行(就绪),等待,等待超时,阻塞,终止)
        //Thread.State
        //使用lambda表达式
        new Thread(() -> {
            for (int i = 0; i < 40; i++) ticket.sale();
        }, "售票员1").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) ticket.sale();
        }, "售票员2").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) ticket.sale();
        }, "售票员3").start();

        //使用匿名内部类
        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //        for (int i = 0; i < 40; i++) {
        //            ticket.sale();
        //        }
        //    }
        //}, "售票员1").start();
        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //        for (int i = 0; i < 40; i++) {
        //            ticket.sale();
        //        }
        //    }
        //}, "售票员2").start();
        //new Thread(new Runnable() {
        //    @Override
        //    public void run() {
        //        for (int i = 0; i < 40; i++) {
        //            ticket.sale();
        //        }
        //    }
        //}, "售票员3").start();
    }
}


